//
//  SYDForgetWordViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/5.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDForgetWordViewController.h"
#import "SYDSocketViewController.h"
@interface SYDForgetWordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UITextField *NewWordField;
@property (weak, nonatomic) IBOutlet UIButton *BackWordBtn;
@property(nonatomic,strong)NSString *phone;
@property(nonatomic,strong)NSString *code;
@property(nonatomic,strong)NSString *word;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeightConstraint;

@end

@implementation SYDForgetWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationBar.title = @"找回登录密码";
    [self navigationBarHandle];
    [self initUI];
}
//获取登录短信验证码
-(void)getLoginSmsCodeFromServer{
    [[SYDNetwork shareTool] getLoginSmsCodeWithMobilePhone:self.phoneTextField.text success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            NSLog(@"responseObject:%@",responseObject);
            if ([responseObject[@"statusCode"]integerValue] == 200) {
                [SVProgressHUD displayInfoWithStatus:@"获取验证码成功,请到手机端查看"];
            }else{
                [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
            }
        } @catch (NSException *exception) {
            NSLog(@"%@",exception.description);
        } @finally {
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD displayInfoWithStatus:@"请检查您的网络"];
    }];
}
#pragma mark---初始化界面
-(void)initUI{
    WEAKSELF
//    self.phoneTextField.placeholderColor = GRAY_COLOR;
//    self.codeTextField.placeholderColor = GRAY_COLOR;
//    self.NewWordField.placeholderColor = GRAY_COLOR;
    [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.codeBtn setTitleColor:GREEN_COLOR forState:UIControlStateNormal];
    self.codeBtn.eventTimeInterval = 3.0;
    [self.phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    if (iPhone8_X) {
        self.topConstraint.constant = 88;
        self.bottomHeightConstraint.constant = 72;
    } else {
        self.topConstraint.constant = 64;
        self.bottomHeightConstraint.constant = 48;
    }
#pragma mark---监听textfield 输入文字
    if (self.phoneTextField.text.length > 0) {
        [self.phoneTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            NSLog(@"电话号码:%@",x);
            weakSelf.phone = x;
        }];
    }
    
    if (self.codeTextField.text.length > 0) {
        [self.codeTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            NSLog(@"验证码:%@",x);
            weakSelf.code  = x;
        }];
    }
    
    if (self.NewWordField.text.length > 0) {
        [self.NewWordField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
            NSLog(@"新密码:%@",x);
            weakSelf.word  = x;
        }];
    }
    //通知
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardDidShowNotification object:nil]subscribeNext:^(NSNotification * _Nullable x) {
        NSLog(@"键盘弹起");
    }];
    
    #pragma mark -- 监听事件(按钮点击)
    //获取验证码
    [[self.codeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self getLoginSmsCodeFromServer];
        [self openCountDown];
    }];
    self.BackWordBtn.eventTimeInterval = 3.0;
    [[self.BackWordBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (weakSelf.phoneTextField.text.length == 0) {
            [SVProgressHUD displayInfoWithStatus:@"请输入手机号"];
        }else if (![NSString justMobile:weakSelf.phoneTextField.text]){
            [SVProgressHUD displayInfoWithStatus:@"输入的手机号有误,请重新输入"];
        }else if (weakSelf.codeTextField.text.length == 0){
            [SVProgressHUD displayInfoWithStatus:@"请输入验证码"];
        }else if (weakSelf.NewWordField.text.length == 0){
            [SVProgressHUD displayInfoWithStatus:@"密码格式不正确,请重新输入"];
        }else{
            [self retrievePasswordFromServer];
//            [SMSSDK commitVerificationCode:self.codeTextField.text phoneNumber:self.phoneTextField.text zone:@"86" result:^(NSError *error) {
//
//                if (!error){
//                    // 验证成功---设置新的登录密码
//                    [self retrievePasswordFromServer];
//                }else{
//                    [SVProgressHUD displayInfoWithStatus:@"验证码错误,请重新输入"];
//                }
//            }];
        }
    }];
}
#pragma mark---获取短信验证码
-(void)getVerificationCode{
    if (![NSString justMobile:self.phoneTextField.text]) {
        [SVProgressHUD displayInfoWithStatus:@"手机号格式有误,请重新输入"];
    }else{
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.phoneTextField.text zone:@"86" result:^(NSError *error) {
            
            if (!error)
            {
                // 请求成功
                [SVProgressHUD displayInfoWithStatus:@"获取验证码成功,请在短信中查看"];
            }
            else
            {
                // error
                NSLog(@"获取验证码失败,%ld",error.code);
            }
        }];
    }
}
#pragma mark---UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField1 shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger pointLength = 0;
    if (textField1 == self.phoneTextField) {
        NSInteger existedLength = textField1.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        pointLength = existedLength - selectedLength + replaceLength;
    }
    //超过16位就不能在输入了
    if (pointLength > 12) {
        return NO;
    }else{
        return YES;
    }
    
}
//然后实现方法：
- (void)textFieldDidChange:(UITextField *)textField
{
    int length = 11;//限制的字数
    NSString *toBeString = textField.text;
    NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage;// 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];       //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position || !selectedRange)
        {
            if (toBeString.length > length)
            {
                NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:length];
                if (rangeIndex.length == 1)
                {
                    textField.text = [toBeString substringToIndex:length];
                }
                else
                {
                    NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, length)];
                    textField.text = [toBeString substringWithRange:rangeRange];
                }
            }
        }
        
    }
}

#pragma mark---获取验证码倒计时
-(void)openCountDown{
    
    __block NSInteger time = 59;//倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_time, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);//每秒执行
    
    dispatch_source_set_event_handler(_time, ^{
        
        if (time <= 0) {
            dispatch_source_cancel(_time);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.codeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                [self.codeBtn setTitleColor:GREEN_COLOR forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.codeBtn setTitle:[NSString stringWithFormat:@"%.2ds后重新获取",seconds] forState:UIControlStateNormal];
                [self.codeBtn setTitleColor:GREEN_COLOR forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_time);
}
#pragma mark - 导航栏
- (void)navigationBarHandle{
    
    WEAKSELF
    [weakSelf backButtonAction:^{
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
//    [weakSelf rightNavButtonWithTitle:@"地图" action:^{
//        
//        [weakSelf.navigationController pushViewController:[[SYDSocketViewController alloc]init] animated:YES];
//    }];
}
-(void)retrievePasswordFromServer{
  [[SYDNetwork shareTool]RetrievePasswordWithPassword:self.NewWordField.text username:self.phoneTextField.text smsCode:self.codeTextField.text success:^(NSURLSessionDataTask *task, id responseObject) {
      @try {
          if ([responseObject[@"statusCode"]integerValue] == 200) {
              [self.navigationController popViewControllerAnimated:YES];
          }else{
              [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
          }
      } @catch (NSException *exception) {
          NSLog(@"exception:%@",exception.description);
      } @finally {
      }
  } failure:^(NSURLSessionDataTask *task, NSError *error) {
      NSLog(@"---%@",error);
  }];
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
